<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class Goods extends Model
{
    protected  $table='goods';

    protected $primaryKey= 'id';

    protected $fillable = [
        'team_id', 'org_id', 'g_name', 'sponsor', 'thumbnail', 'g_img', 'content', 'access', 'type','price', 'points', 'g_num', 'u_num', 'auto_time','examine', 'is_display','condition', 'start_time', 'end_time'
    ];

    public function team_info()
    {
        return $this->hasOne('App\Models\Team', 'id', 'team_id');
    }
    public function order_info()
    {
        return $this->hasOne('App\Models\Order', 'goods_id', 'id');
    }

    public function org_info()
    {
        return $this->hasOne('App\Models\Org', 'id', 'org_id');
    }

    public function getStartTimeAttribute() {
        if (isset($this->attributes['start_time'])) {
            $date = new Carbon($this->attributes['start_time']);
            return $date->getTimestamp();
        }

        return null;
    }

    public function setStartTimeAttribute($value) {
        $value = strtotime(date('Y-m-d', $value).' 00:00:00');

        $date = new Carbon();
        $date->setTimestamp($value);

        $this->attributes['start_time'] = $date->toDateTimeString();
    }

    public function getEndTimeAttribute() {
        if (isset($this->attributes['end_time'])) {
            $date = new Carbon($this->attributes['end_time']);
            return $date->getTimestamp();
        }

        return null;
    }

    public function setEndTimeAttribute($value) {
        $value = strtotime(date('Y-m-d', $value).' 23:59:59');

        $date = new Carbon();
        $date->setTimestamp($value);
        $this->attributes['end_time'] = $date->toDateTimeString();
    }

    public function getAutoTimeAttribute() {
        if (isset($this->attributes['auto_time'])) {
            $date = new Carbon($this->attributes['auto_time']);
            return $date->getTimestamp();
        }

        return null;
    }

    public function setAutoTimeAttribute($value) {
        $value = strtotime(date('Y-m-d', $value).' 23:59:59');

        $date = new Carbon();
        $date->setTimestamp($value);
        $this->attributes['auto_time'] = $date->toDateTimeString();
    }
}